<template>
  <template v-if="listLoading === false">
    <WelcomeContainer
      v-if="
        (MessageList.length === 0 ||
          (MessageList.length === 1 && MessageList[0].type === 'received')) &&
        !props.isDocument &&
        !guideContent
      "
      class="welcome-container"
      @sendMessage="guideSend"
      @receive-welcome="receiveWelcome"
    ></WelcomeContainer>

    <div v-else class="chat-room-container">
      <header-title
        v-if="!props.isDocument"
        :title="questionTitle"
        :dialog-id="dialogId"
        :isFromShare="isFromShare"
      >
        <span class="chatCreatedTime">{{ chatCreatedTime }}</span>
      </header-title>
      <div
        ref="containerRef"
        class="chat-room"
        :style="{ height: !props.isDocument ? 'calc(100vh - 61px)' : '100%' }"
      >
        <div ref="chatRef" class="chat-room-inside" :class="{ 'doc-background': props.isDocument }">
          <div
            ref="chatHistoryEle"
            class="chat-history"
            :class="{ 'doc-background': props.isDocument }"
            @scroll="onScroll"
          >
            <div class="message-list">
              <div
                class="welcome-msg"
                v-if="
                  MessageList.length === 0 ||
                  (MessageList.length === 1 && MessageList[0].type === 'received')
                "
              >
                {{ guideContent || welcomeMsg }}
              </div>
              <a-checkbox-group v-show="isSelecting" v-model:value="shareSelectState.checkedList">
                <a-checkbox
                  :value="chat.id"
                  v-for="(chat, index) in MessageList"
                  :key="chat.id || chat.fakeId"
                >
                  <MessageItem
                    :class="{ 'doc-background': props.isDocument }"
                    :key="chat.id || chat.fakeId"
                    v-bind="chat"
                    :is-last-one="index === MessageList.length - 1"
                    @strong-ask="strongAsk"
                    @resend-chat="resendChat"
                    @share-chat="shareChat"
                    @click-quote-item="onClickQuoteItem"
                    @click-related-item="onClickRelatedItem"
                    @show-detail="showDetail"
                    @close-reference="closeReference"
                    @update-content="toBottom"
                    @vote-change="handleClearContext"
                    @page-change="handlePageChange"
                  />
                </a-checkbox>
              </a-checkbox-group>
              <MessageItem
                v-show="!isSelecting"
                v-for="(chat, index) in MessageList"
                :class="{ 'doc-background': props.isDocument }"
                :key="chat.id || chat.fakeId"
                v-bind="chat"
                :is-last-one="index === MessageList.length - 1"
                @strong-ask="strongAsk"
                @resend-chat="resendChat"
                @share-chat="shareChat"
                @click-quote-item="onClickQuoteItem"
                @click-related-item="onClickRelatedItem"
                @show-detail="showDetail"
                @close-reference="closeReference"
                @update-content="toBottom"
                @vote-change="handleClearContext"
                @page-change="handlePageChange"
              />
            </div>
          </div>
          <div v-if="!isSelecting && !isFromShare" class="chat-input">
            <div class="text-tools-wrap">
              <template v-if="!props.isDocument">
                <div ref="target">
                  <div v-if="selectVisible" class="button-list">
                    <div
                      v-for="item in answerTypeList"
                      :key="item.value"
                      class="answerTypeItem"
                      @click="selectAnswerType(item)"
                    >
                      <img
                        class="answerTypeIcon"
                        :src="getImgUrl(`static/image/${item.value}-icon.png`)"
                      />
                      {{ item.label }}
                    </div>
                  </div>
                  <div v-else class="button-list singleTypeItem">
                    <div class="answerTypeItem" @click="onClickAnswerBtn">
                      <img
                        class="answerTypeIcon"
                        :src="getImgUrl(`static/image/${answerType.value}-icon.png`)"
                      />
                      {{ answerType.label }}
                    </div>
                  </div>
                </div>
                <div style="opacity: 0; width: 110px"></div>
              </template>

              <a-textarea
                ref="textarea"
                v-model:value="currentMessage"
                type="text"
                confirm-type="send"
                :maxlength="2024"
                :cursor-spacing="30"
                :show-confirm-bar="false"
                :autofocus="true"
                allow-clear
                placeholder="请分享您的研究场景、技术难点或创新设想，我们可以深入探讨解决方案。"
                :auto-size="{ minRows: 1, maxRows: 5 }"
                class="textarea-wrap"
                @keydown="onkeydown"
                @confirm="onConfirm"
                @input="onInputChange"
              />
              <div
                v-if="props.isDocument && props.processStatus < 6"
                ref="ansyizeing"
                class="ansyizeing"
              ></div>
              <template v-else>
                <div
                  v-if="sentPending"
                  type="primary"
                  class="btn-stop-send flex-none"
                  :class="{
                    disabled: isDisabledAsk
                  }"
                  @click="onClickSendBtn"
                />
                <div
                  v-else
                  type="primary"
                  class="btn-send flex-none"
                  :class="{
                    disabled: isDisabledAsk
                  }"
                  @click="onClickSendBtn"
                />
              </template>
            </div>
            <!-- <div class="space-between action-area">
            <div
              v-if="MessageList.length && !isSelecting"
              class="flex clear-records"
              @click="handleClearContext"
            >
              <div :class="inputType" class="icon-brush-wrap flex-none">
                <img src="@/assets/brush.png" mode="aspectFill" alt="" class="icon-brush" />
              </div>
              清除记录
            </div>

              <div class="flex enhance-btn">
                <a-switch v-model:checked="enhence" size="small" />
                <span @click="switchEnhance">增强&nbsp;</span>
              </div>
            </div> -->
          </div>
          <div v-else-if="isSelecting" class="chat-input">
            <div class="from-share-btns">
              <a-checkbox
                v-model:checked="shareSelectState.checkAll"
                :indeterminate="shareSelectState.indeterminate"
                @change="onCheckAllChange"
              >
                全选
              </a-checkbox>
              <div class="copy-area flex">
                <span @click="cancelSelect" class="mr16">返回对话</span>
                <span class="btn-primary" @click="copyLink">复制链接</span>
              </div>
            </div>
          </div>
          <div v-else-if="isFromShare" class="chat-input">
            <div class="from-share-btns">
              <template v-if="user.frontToken">
                <span @click="createdNewChat">新建对话</span>
                <span @click="continueChat" class="btn-primary" >继续对话</span>
              </template>
              <template v-else>
                <router-link class="btn-normal" to="/applyTest">申请试用</router-link>
                <span @click="goLogin" class="btn-primary">用户登录</span>
              </template>
            </div>
          </div>

          <a-drawer
            placement="right"
            :closable="false"
            :visible="currentPaperVisible"
            :get-container="false"
            :style="{ position: 'absolute' }"
            width="100%"
            @close="closeCurrentPage"
          >
            <PaperItem
              v-if="currentPaper"
              :detail="true"
              :paper="currentPaper"
              @close-drawer="closeCurrentPage"
            />
          </a-drawer>
          <div v-show="isToTopStatus" class="to-bottom-btn" @click="clickToBottom">
          </div>
        </div>
        <!-- <div ref="dividerRef" class="divider" ></div> -->
        <ReferenceContent
          ref="referenceContent"
          class="reference-content"
          :visible="showPaperList"
          v-model:value="showPaperList"
          v-model:currentPaper="currentPaper"
          :ids="ids"
          :referenceIndex="referenceIndex"
          @close-reference="closeReference"
        ></ReferenceContent>
      </div>
    </div>
  </template>
  <template v-else>
    <div class="no-data"><a-spin size="large" /></div>
  </template>
</template>

<script lang="ts" setup>
import { getDateStr, transformRelateArticle, loadFromLocal, scroll, getDate, isJSON } from '@/utils'
import {
  apiAnswerFeedback,
  apiAskGPT,
  apiChatHistory,
  ASK_TYPE,
  apiStopQuestion,
  apiShareRecorder,
  apiShareRecorderList
} from '@/api/dialog'
import { cloneDeep, debounce, delay, keyBy, omit, throttle } from 'lodash'
import { apiGetDialogDetail } from '@/api/dialog'
import lottie, { type AnimationItem } from 'lottie-web'
import {
  type ComponentPublicInstance,
  computed,
  onBeforeMount,
  ref,
  nextTick,
  watch,
  onMounted,
  provide,
  onBeforeUnmount,
  reactive
} from 'vue'
import { useSocket } from '@/hook/useSocket'
import { type Article, type MainItemVo, ENodeType, EAnswerState, type GuideItem } from '@/api/type'
import { type IMstPaper } from '@/api/dialog'
import { message as msgHelper } from 'ant-design-vue'
import { setLocal } from '@/utils/local'
import { useRoute, useRouter } from 'vue-router'
import { useUserInfoStore } from '@/stores/modules/userInfo'
import { useChatBus } from '@/hook/useChatBus'
// import { updateSearchType } from '@/api/user'
import MessageItem from './MessageItem.vue'
import WelcomeContainer from './WelcomeContainer.vue'
import { getImgUrl } from '@/utils/index'
import { inject } from 'vue'
import ReferenceContent from './ReferenceContent.vue'
import { apiCopilotWelcome } from '@/api/manage'
import { onClickOutside, useClipboard } from '@vueuse/core'

defineOptions({
  name: 'ChatRoom'
})
interface delautItem {
  label?: string
  value?: string
  type?: string
}
const parse = JSON.parse
const props = defineProps({
  sessionId: {
    type: String,
    default: ''
  },
  isDocument: {
    //是否是文档解析
    type: Boolean,
    default: false
  },
  parentDialogId: {
    type: String,
    default: ''
  },
  processStatus: {
    type: Number,
    default: 3
  },
  pdfId: {
    type: String,
    default: ''
  }
})
const currentPaper = ref<IMstPaper>()
const CHAT_INPUT = 'CHAT_INPUT'
// 声明一个 ref 来存放该元素的引用
// 必须和模板里的 ref 同名
const chatHistoryEle = ref<HTMLDivElement>()
// const onClickChatItem = (chat: any) => {
//   if (!isSelecting.value) return
//   toggleCheckbox(chat)
// }
const currentPaperVisible = computed(() => (currentPaper.value ? true : false))
const enhence = ref(true)
// watch(enhence, () => {
//   if (!userId) return
//   updateSearchType({
//     id: userId,
//     searchType: enhence.value ? 1 : 0
//   })
// })
const switchEnhance = () => {
  enhence.value = !enhence.value
}

const user = useUserInfoStore()
const listQuery = ref({
  current: 1,
  limit: 50,
  customerId: ''
})
const referenceIndex = ref<string>('')
const route = useRoute()
const router = useRouter()
const dialogId = computed(() => (route.params.id || props.parentDialogId) ?? '')
const showPaperList = ref(false)
const questionTitle = ref<string>('')
const chatCreatedTime = ref<string>('')
const getQuestionTitle = inject('getQuestionTitle', () => {}) as (
  title: string,
  time?: string
) => void
const createdNewChat = () => {
  bus.emit('createdNewChat')
}

const continueChat = () => {
  bus.emit('createdNewChat',{ shareId: route.params.id,dialogName: questionTitle.value })
}

const toggleCheckbox = (item: MainItemVo) => {
  const id = item.id as string
  const index = selectedIds.value.indexOf(id)
  const exist = index !== -1
  if (exist) selectedIds.value.splice(index, 1)
  else selectedIds.value.push(id)
}
const MessageList = ref<Array<MainItemVo>>([])

const enhenceMessageList = computed(() =>
  MessageList.value.map((o, index) => {
    const isLastOne = index === MessageList.value.length - 1
    if (!isLastOne) return o
    return {
      ...o,
      isLastOne
    }
  })
)
const hasInitChat = ref(false)
// const recommendList = ref<Array<recommand>>([])
const inputType = ref('text') // text=文本输入   audio=语音输入
const currentMessage = ref(loadFromLocal(CHAT_INPUT) ?? '')
const isSelecting = ref(false) //是否处于 多选状态
const isFromShare = computed(() => {
  return route.path.includes('loginShareMessage')
})
type strArr = Array<string>
const listLoading = ref(false)
const selectedIds = ref<strArr>([])
const allDataReadOut = ref(false) //所有的对话数据是否已经读取完毕了
const pageState = ref('')
// const sessionId = ref(`${dialogId.value}_${Date.now()}`) //上下文的会话id
const issocketClose = ref(false) //是否已经p打开了websocket
const failQuestionId = ref<strArr>([]) //没有回复的问题id
const sentPending = ref(false) //上一个信息还在发送中 button需要disabled
const answerTypeList = ref<delautItem[]>([
  {
    label: '即答',
    value: 'immediately',
    type: '0'
  },
  {
    label: '全部',
    value: 'all',
    type: '1'
  },
  {
    label: '论文',
    value: 'paper',
    type: '2'
  },
  {
    label: '专利',
    value: 'patent',
    type: '3'
  }
])
const answerType = ref<delautItem>({
  label: '全部',
  value: 'all',
  type: '1'
})
const questionType = ref<number>(0)
const target = ref(null)
const guideContent = ref('') //从引导页过来的引导内容
onClickOutside(target, () => {
  selectVisible.value = false
})
// 选择提问类型
const selectAnswerType = (data: delautItem) => {
  console.log(data)
  answerType.value = data
  selectVisible.value = false
}
const selectVisible = ref(false)
// 点击提问类型按钮
const onClickAnswerBtn = () => {
  selectVisible.value = true
}

watch(dialogId, () => getMainList())

const messageTrim = computed(
  () => currentMessage.value?.replace(/^(\s|\n|\r|\r\n)+|(\s|\n|\r|\r\n)+$/g, '')
)
const sessionIdValue = ref<string>('')
onBeforeMount(async () => {
  pageState.value = 'ON_LOAD'
  await getMainList()
  if (MessageList.value.length > 0) {
    if (!props.isDocument) {
      answerType.value = answerTypeList.value.filter(
        (o) => o.type === MessageList.value[MessageList.value.length - 1].searchType
      )[0]
    }

    if (MessageList.value[MessageList.value.length - 1].replyState === 0) {
      sentPending.value = true
      sessionIdValue.value =
        MessageList.value[MessageList.value.length - 1].sessionId || props.sessionId
    } else {
      sessionIdValue.value = props.sessionId
    }
  } else {
    sessionIdValue.value = props.sessionId
    console.log('sessionIdValue', sessionIdValue.value)
  }
  console.warn('sessionIdValue', sessionIdValue.value)
  if (!props.isDocument && MessageList.value.length > 0 && !isFromShare.value) {
    getDialogDetail()
  }
  if (!isFromShare.value) {
    getPresupposeList()
  }
})
const textarea = ref<HTMLInputElement | ComponentPublicInstance>()
onMounted(() => {
  initLottie()
  ;(textarea?.value as HTMLInputElement)?.focus()
})

// TODO  跳转或者打开文献详情
const onClickQuoteItem = (item: Article) => {
  console.log(item)
}
//TODO 这里的userId需要替换
const userId = user.id
const ids = ref('')
function showDetail(chat: MainItemVo, index?: number) {
  if (props.isDocument) return
  const idlist = chat.resourceIds?.join(',') || '83563e3001e240318b7c0f2a37aa56e2'
  nextTick(() => {
    referenceIndex.value = (index && index.toString()) || ''
  })
  localStorage.setItem('__PAPER__IDS__', idlist)
  ids.value = idlist
  updateOpenIndex(chat)
  showPaperList.value = true
}

const closeReference = () => {
  MessageList.value.forEach((m) => (m.opened = false))
  showPaperList.value = false
}

function strongAsk(chat: MainItemVo) {
  enhence.value = true
  delay(() => {
    if (sentPending.value) return
    const question = MessageList.value.find((o) => o.questionId === chat.questionId)

    const questionContent = chat?.questionContent ?? question?.message

    sendQuestion({
      message: questionContent
    })
  }, 200)
}

const questionMap = computed(() => {
  return keyBy(
    MessageList.value.filter((o) => o.type === 'sent'),
    (o) => o.questionId
  )
})

const updateOpenIndex = (chatItem: MainItemVo) => {
  const needOpenIndex = MessageList.value.findIndex((o) => o.id === chatItem.id)
  if (needOpenIndex > -1) {
    MessageList.value.forEach((ch) => (ch.opened = false))
    MessageList.value[needOpenIndex].opened = true
  }
}

const getMainList = async ({ pullingDown = false } = {}) => {
  try {
    let resp
    if (isFromShare.value) {
      resp = await apiShareRecorderList(dialogId.value as string)
    } else {
      getWelcomeMsg()
      if (listLoading.value) {
        return
      }
      if (!userId || !dialogId.value) {
        return
      }
      if (pullingDown) {
        listQuery.value.current++
      } else {
        listQuery.value.current = 1
      }
      const queryData = {
        ...listQuery.value,
        customerId: userId,
        dialogId: dialogId.value as string,
        userId: userId
      }
      listLoading.value = true

      resp = await apiChatHistory(queryData)
    }

    const {
      data: { entity = {} }
    } = resp
    const rows = (isFromShare.value ? entity?.copilotConversationVOList : entity.rows) || []
    isFromShare.value && (questionTitle.value = entity?.copilotConversationShareVO?.shareDialogName)
    if (rows && rows.length === 0) {
      //目前接口没有数据就是返回[],不会返回null
      allDataReadOut.value = true //所有的数据都已经读取完毕
    }

    const QAList: any = rows.reduce((acc, cur) => {
      if (cur?.answerContentList && isJSON(cur.answerContentList)) {
        cur.answerContentList = JSON.parse(cur.answerContentList)
        cur.currentNodeMessage = cur.answerContentList.at(-1) || {}
      }
      if (cur?.searchingList && isJSON(cur.searchingList)) {
        cur.searchingList = JSON.parse(cur.searchingList as unknown as string)
      }
      if (cur?.thinkingContent && isJSON(cur.thinkingContent)) {
        cur.thinkingContent = JSON.parse(cur.thinkingContent as unknown as string)
      }
      cur.isHistory = true
      acc.push(cur)
      return acc
    }, [])

    const chats: Array<MainItemVo> = []

    // console.log('QAList', QAList)
    let prevFirstItem = MessageList.value.length && MessageList.value[0]
    // let lastItem
    // questionTitle.value = route.query?.questionTitle as string || rows[0]?.questionContent
    questionType.value = rows[0]?.questionType
    chatCreatedTime.value = getDate(rows[0]?.createdTimestamp)
    console.log('questionTitle', props.isDocument)
    // if (props.isDocument) {
    //   getQuestionTitle(questionTitle.value, chatCreatedTime.value)
    // }

    QAList.forEach((QAItem) => {
      const Q = {
        ...QAItem,
        groupId: QAItem.id,
        id: QAItem.questionId, // 原始的id
        questionId: QAItem.questionId, // 问题的id
        fakeId: `id_${QAItem.questionId}`, // uniapp中元素的id不能以字母开头
        message: QAItem.questionContent,
        // plainText: QAItem.questionContent,
        type: 'sent',
        contentType: QAItem.questionUrl ? 'audio' : 'text',
        questionUrl: QAItem.questionUrl,
        duration: QAItem.duration,
        relatedArticles: transformRelateArticle(QAItem.relatedArticles),
        date: getDateStr(QAItem.createdTimestamp)
      }
      const A = {
        ...QAItem,
        groupId: QAItem.id,
        id: QAItem.answerId, // 原始的id
        questionId: QAItem.questionId, // 问题的id
        fakeId: `id_${QAItem.answerId}`, // uniapp中元素的id不能以字母开头
        message: QAItem.answerContent,
        // plainText: QAItem.answerContent,
        type: 'received',
        contentType: 'text',
        hasSupport: QAItem.hasSupport,
        date: getDateStr(QAItem.answerTimestamp),
        suggestQuestionList: QAItem.suggestQuestionList,
        relatedArticles: transformRelateArticle(QAItem.relatedArticles),
        responseState: QAItem.responseState,
        replyState: QAItem.replyState
      }

      chats.push(Q)

      chats.push(A)

      if (QAItem.hasCleanLine) {
        const cleanItem = {
          id: QAItem.id,
          fakeId: `id_${QAItem.id}`,
          contentType: 'clear'
        }
        chats.push(cleanItem)
      }
    })

    if (pullingDown) {
      MessageList.value.unshift(...chats)
      nextTick(() => {
        if (chats.length === 0 || !prevFirstItem) return
      })
    } else {
      MessageList.value = chats.map((v) => ({ ...v, opened: false }))
      if (chats.length && !showPaperList.value) {
        const lastHasReference = [...chats]
          .reverse()
          .find((c) => c.resourceIds?.length && c.queryType === 1 && c.replyState !== 2)
        if (lastHasReference) {
          showDetail(lastHasReference)
        }
      }
    }
    hasInitChat.value = true
    setTimeout(() => {
      listLoading.value = false
    }, 1000)
    if (!pullingDown && !MessageList.value.length) {
      getPresupposeList()
    }
  } catch (e) {
    console.info(e)
  }
}

const welcomeMsg = ref('')
const getWelcomeMsg = async () => {
  const {
    data: { entity = {} }
  } = await apiCopilotWelcome({ type: props.isDocument ? 2 : 1 })
  welcomeMsg.value = entity?.content || ''
}

const getPresupposeList = async () => {}
const isToTopStatus = ref(false)
const lastScrollTop = ref(0)
const onScroll = (e: Event) => {
  const target = e.target as HTMLElement
  const { scrollTop, clientHeight, scrollHeight } = target
  if (scrollTop + clientHeight === scrollHeight) {
    isToTopStatus.value = false
  }
  let scrollStep = scrollTop - lastScrollTop.value
  lastScrollTop.value = scrollTop
  if (scrollStep < 0) {
    isToTopStatus.value = true
  }
}
function toBottom() {
  // console.log('to bootom call')
  if (!chatHistoryEle.value || isToTopStatus.value) return
  chatHistoryEle.value.scrollTo({ top: chatHistoryEle.value.scrollHeight, behavior: 'smooth' })
}

const clickToBottom = () => {
  console.warn(123123)

  isToTopStatus.value = false
  toBottom()
}

const debounceToBottom = debounce(toBottom, 200)

const sockeId = computed(() => `${user.id}_${sessionIdValue.value}`)
let socket: any = null
watch(sockeId, () => {
  console.log('sockeId change', sockeId.value)
  if (sessionIdValue.value && sockeId.value.length > 50) {
    nextTick(() => {
      socket = useSocket(socketOptions, sockeId)
    })
  }
})

const socketOptions = {
  autoReconnect: {
    delay: 200
  },

  onConnected(ws: WebSocket) {
    console.log('connect success', ws)
  },
  onError(ws: WebSocket) {
    console.error('connect error ', ws)
  },
  onDisconnected() {
    console.warn('连接中断')
    // socketClose()
  },
  onMessage(_wx: WebSocket, evt: MessageEvent) {
    // console.log('mainList.value.', MessageList.value)
    if (MessageList.value.filter((o) => o.type === 'received').length === 0) {
      console.log('onMessage', MessageList)
      bus.emit('refreshDiaglogName')
    }
    insertChatItem(parse(evt.data))
  }
}

const bus = useChatBus((e, val) => {
  switch (e) {
    case 'setEnhence':
      enhence.value = val ? true : false
  }
})
const { close: socketClose } = useSocket(socketOptions, sockeId)

const stopSentPending = () => {
  console.log('stopSentPending')
  sentPending.value = false
  bus.emit('refreshDiaglogName')
}

interface socketDataItem extends MainItemVo {
  id: string
  questionId: string
  answerId: string
  text: string
  connected: '0' | '1'
}

const insertChatItem = (wsItem: socketDataItem) => {
  if (wsItem.connected === '1') {
    // notifyConnected()
  }
  if (!wsItem.id) {
    return
  }
  console.warn(wsItem, 'wsItem')

  const isReplyFinished = !!wsItem.replyState
  const isLoading = !isReplyFinished && !wsItem.text
  if (isReplyFinished) {
    stopSentPending()
  }
  if (wsItem?.answerContentList?.length && isJSON(wsItem.answerContentList)) {
    wsItem.answerContentList = JSON.parse(wsItem.answerContentList)
  }
  //交互效果 27232 http://192.168.30.34:81/zentao/bug-div-27232.html
  const suggestQuestionList = isReplyFinished ? wsItem.suggestQuestionList : []
  const questionContent = questionMap.value?.[wsItem.questionId]
  console.log('questionContent', questionContent)

  const isMultiNode = wsItem.nodeType === ENodeType.MULTI_NODE
  let currentNodeMessage = null
  if (isMultiNode) {
    currentNodeMessage = wsItem.answerContentList.at(-1) || {}
  }
  const answer = cloneDeep(
    Object.assign({}, questionContent, {
      ...omit(wsItem, ['text']),
      id: wsItem.answerId || wsItem.id,
      groupId: wsItem.id,
      questionId: wsItem.questionId,
      fakeId: `id_${wsItem.answerId}`,
      suggestQuestionList,
      relatedArticles: transformRelateArticle(wsItem.relatedArticles),
      responseState: wsItem.responseState, //响应状态 1正常数据 2响应超时 3网络异常 4回答中断
      type: 'received',
      contentType: 'text',
      isLoading,
      hasSupport: 0,
      date: getDateStr(wsItem.createdTimestamp),
      message: wsItem?.text ?? '',
      answerContentList: wsItem?.answerContentList?.map((c, i) => ({
        ...c,
        message: c.answerContent,
        id: `${wsItem.answerId}_${i}`
      })),
      currentNodeMessage,
      isAnswering: true
    })
  )
  console.warn(answer, 'answer111')
  const idlist = wsItem.resourceIds?.join(',') || ''
  localStorage.setItem('__PAPER__IDS__', idlist.length > 0 ? idlist : ids.value)
  ids.value = idlist.length > 0 ? idlist : ids.value
  if (
    idlist.length > 0 &&
    showPaperList.value == false &&
    !props.isDocument &&
    answerType.value.type != 0
  ) {
    showPaperList.value = true
  }
  // console.log('insert new answer', answer)
  console.log(`insert new answer text type:${typeof answer.message}`, answer.message)
  const AnswerIndex = MessageList.value.findIndex(
    (item) => (item.groupId === answer.groupId && item.type === 'received') || item.id === answer.id
  )

  const QuestionIndex = MessageList.value.findIndex(
    (item) => item.groupId === answer.groupId && item.id !== answer.id
  )

  if (AnswerIndex === -1 && QuestionIndex === -1) {
    MessageList.value.push(answer)
    !!idlist.length && updateOpenIndex(answer)
    toBottom()
    return
  }

  // console.log('直接替换')
  if (AnswerIndex !== -1) {
    // 这里做更新操作
    // MessageList.value.splice(AnswerIndex, 1, answer)
    // 中断回来之后，这里要判断一下之前的，如果是多节点，和现在的answer判断一下 answerContentList
    const answerContentList = MessageList.value[AnswerIndex].answerContentList
    if (MessageList.value[AnswerIndex]?.isFlowing && isMultiNode) {
      answer.isFlowing = true
      const flowingIndex = answerContentList?.findIndex(
        (c) => c.answerState === EAnswerState.ANSWERING
      )
      answer?.answerContentList?.forEach((element) => {
        element.isFlowing = false
      })
      flowingIndex !== -1 && (answer.answerContentList[flowingIndex].isFlowing = true)
    }
    console.warn(
      !MessageList.value[AnswerIndex]?.isFlowing &&
        isMultiNode &&
        MessageList.value[AnswerIndex].isHistory,
      '147258369',
      !MessageList.value[AnswerIndex]?.isFlowing,
      isMultiNode,
      MessageList.value[AnswerIndex].isHistory
    )

    if (
      !MessageList.value[AnswerIndex]?.isFlowing &&
      isMultiNode &&
      MessageList.value[AnswerIndex].isHistory &&
      answerContentList?.length
    ) {
      const historyFlowingIndex = answerContentList?.findLastIndex(
        (a) => a.answerState === EAnswerState.ANSWERING
      )
      console.warn(historyFlowingIndex, 'historyFlowingIndex')

      if (historyFlowingIndex !== -1) {
        answer.answerContentList[historyFlowingIndex] &&
          (answer.answerContentList[historyFlowingIndex].isFlowing = true)
        answer.isFlowing = true
        answer.answerContentList.forEach((listItem, i) => {
          if (i < historyFlowingIndex) {
            listItem.isHistory = true
          }
        })
      }
      MessageList.value[AnswerIndex].isHistory = false
      answer.isHistory = false
    }
    MessageList.value[AnswerIndex] = answer

    !!idlist.length && updateOpenIndex(answer)
    toBottom()
    return
  }

  //插到问题后面的第一个位置
  if (QuestionIndex !== -1) {
    MessageList.value.splice(QuestionIndex + 1, 0, answer)
    !!idlist.length && updateOpenIndex(answer)
    toBottom()
    return
  }
}
const receiveWelcome = (data: GuideItem) => {
  guideContent.value = data.content as string
  questionType.value = data.questionType || 0
}
const guideSend = async ({ title, type }: { title: string; type: delautItem }) => {
  answerType.value = type
  sendQuestion({ message: title })
}

const resendChat = async (chat: MainItemVo) => {
  if (MessageList.value?.filter((c) => c.type === 'received')?.length === 1) {
    MessageList.value.forEach((ch) => (ch.opened = false))
    ids.value = ''
    showPaperList.value = false
  }
  if (sentPending.value) return
  console.log('resendChat', chat)
  await sendQuestion({
    rsId: chat.id,
    message: chat.questionContent,
    replyAgain: true,
    quesstionId: chat.questionId
  })
  let lastItem = MessageList.value.filter((item) => item.questionId === chat.questionId).pop()
  if (lastItem) {
    MessageList.value.splice(MessageList.value.indexOf(lastItem), 1)
  }
  console.log('resendChat', MessageList.value)
}

const shareChat = (chat: MainItemVo) => {
  console.warn(chat,'chat');
  //  回答和提问都要选中，判断一下
  shareSelectState.checkedList.push(chat.id as string)
  if(chat.type === 'received'){
    shareSelectState.checkedList.push(chat.questionId as string)
  }
  if(chat.type === 'sent') {
    const isAnswerExist = MessageList.value.filter((item) => item.id === chat.answerId).length
    isAnswerExist && (shareSelectState.checkedList.push(chat.answerId as string))
  }
  shareSelectState.checkedList = [...new Set([...shareSelectState.checkedList])]
  isSelecting.value = true
}

const emit = defineEmits(['updateSessionId'])
async function handleClearContext(_chat: MainItemVo, type: number) {
  console.log('handleClearContext', _chat)
  // behaviorType:0 -取消 1-点赞，2 -踩，3-分享 4-清理聊天记录
  await apiAnswerFeedback({
    behaviorType: type,
    dialogId: dialogId.value as string,
    answerId: _chat.answerId
  })
  console.log('handleClearContext', MessageList.value, _chat.answerId)
  MessageList.value.forEach((item, index) => {
    if (item.answerId === _chat.answerId) {
      item.hasSupport = type
    }
  })
}
const getDialogDetail = async () => {
  const {
    data: { entity }
  } = await apiGetDialogDetail(dialogId.value as string)
  const dialogDetail = entity
  questionTitle.value = dialogDetail.dialogName
  getQuestionTitle(dialogDetail.dialogName, chatCreatedTime.value)
}

interface IPending {
  questionId: string
  delay: number
}
function startSentPending() {
  sentPending.value = true
}

const stopWaitingAnswerTimeout = ref()
async function sendQuestion({
  message = '',
  rsId = '', //发送失败的id
  resend = false,
  duration = 0,
  replyAgain = false,
  quesstionId = '',
  audioUrl = '' //音频的url 现在不需要发送音频了 都是直接转文字后发送
} = {}) {
  console.log('sendQuestion', dialogId.value)
  message = message || messageTrim.value
  if (!audioUrl && !message) {
    msgHelper.error('提问词语不能为空')
    return false
  }
  if (!audioUrl && message.length > 2024) {
    msgHelper.error('提问字数不能超过2024')
    return false
  }
  currentMessage.value = ''
  setLocal(currentMessage, CHAT_INPUT)
  const timestamp = Date.now()
  const questionId = quesstionId || `${timestamp}`
  startSentPending()
  return new Promise((resolve, reject) => {
    const queryData = {
      dialogId: dialogId.value as string,
      sessionId: sessionIdValue.value,
      questionId,
      questionContent: message,
      searchType: answerType.value.type,
      queryType: !props.isDocument ? 1 : 2, // 普通提问1 ，文档解读2
      isHomePage: route.name === 'chatDefault' && !props.isDocument ? 1 : 0,
      replyAgain: replyAgain ? 1 : 0,
      pdfId: props.pdfId || '',
      questionType: questionType.value
    }
    //如果是报错重发的，先删除报错的
    if (resend) {
      const targetErrIndex = MessageList.value.findIndex((item) => item.id === rsId)
      MessageList.value.splice(targetErrIndex, 1)
    }

    // const selfIndex = MessageList.value.findIndex((item) => item.id === rsId)
    // const sentLoading = {
    //   id: questionId,
    //   fakeId: `id_${questionId}`,
    //   type: 'sent',
    //   isLoading: true
    // }

    // if (selfIndex === -1) {
    //   MessageList.value.push(sentLoading)
    // } else {
    //   // 可能之前是error占了一个位置
    //   MessageList.value.splice(selfIndex, 1, sentLoading)
    // }

    const handleError = (error: Error | string) => {
      stopSentPending()

      //去除isLoading
      const targetIndex = MessageList.value.findIndex((item) => item.id === questionId)
      MessageList.value.splice(targetIndex, 1)

      const timestamp = Date.now()
      const id = `${timestamp}`

      MessageList.value.push({
        id: id,
        fakeId: `id_${id}`,
        type: 'sent',
        error: true,
        contentType: audioUrl ? 'audio' : 'text',
        duration: Number(duration),
        questionUrl: audioUrl,
        date: getDateStr(),
        message: message
      })

      reject(error)
    }
    /**
     * 调用 askGPT接口
     */

    apiAskGPT(queryData)
      .then((res) => {
        const ok = res.data.ok
        if (!ok) {
          handleError(message)
          return
        }

        const { id: groupId, questionContent, questionId, createdTimestamp } = res.data.entity
        if (stopWaitingAnswerTimeout.value) {
          clearTimeout(stopWaitingAnswerTimeout.value)
        }
        if (user.replyExpireTime) {
          stopWaitingAnswerTimeout.value = setTimeout(() => {
            stopWaitingAnswerTimeout.value = undefined
            const curAnswerItem = MessageList.value.find(
              (item) => item.questionId === questionId && item.type === 'received'
            )
            if (curAnswerItem && (curAnswerItem?.answerState || 0) < EAnswerState.FINISH_ANSWER) {
              stopQuestion(3)
            }
          }, user.replyExpireTime)
        }

        if (MessageList.value.length === 1) {
          // 初次提问，更新标题
          props.isDocument
            ? getQuestionTitle(queryData.questionContent, getDate(new Date().getTime()))
            : (questionTitle.value = queryData.questionContent)
        }

        console.log('问题发送成功时 issocketClose =', issocketClose)
        if (!issocketClose.value) {
          failQuestionId.value.push(questionId)
        }
        //移除sentLoading
        const selfIndex = MessageList.value.findIndex((item) => item.id === questionId)
        const receivedChat = {
          ...queryData,
          groupId,
          questionId,
          id: questionId,
          fakeId: `id_${questionId}`,
          type: 'sent',
          contentType: audioUrl ? 'audio' : 'text',
          duration: Number(duration),
          questionUrl: audioUrl,
          date: getDateStr(createdTimestamp),
          message: questionContent ?? message,
          transAudioToText: questionContent
        }
        console.log('ask question', receivedChat)
        if (selfIndex === -1) {
          MessageList.value.push(receivedChat)
        } else {
          MessageList.value.splice(selfIndex, 1, receivedChat)
        }
        resolve(true)
        startWaitingAnswer({ questionId })
      })
      .catch((error: Error) => {
        handleError(error)
      })
  })
}
interface stopQuestionParams {
  dialogId: string
  sessionId: string
  questionId: string
  answerContent: string
  replyState: number // 0回答未完毕 1回答完毕  2回答中断 3响应超时
}
const stopQuestion = async (replyState: number = 2) => {
  if (sentPending.value) {
    const timestamp = Date.now()
    const questionId = `${timestamp}`
    // const message = messageTrim.value
    const lastItem = MessageList.value[MessageList.value.length - 1]
    console.log('stopQuestion', JSON.stringify(lastItem))
    if (!lastItem?.questionId) return
    socket.close()
    emit('updateSessionId')
    const queryData: stopQuestionParams = {
      dialogId: dialogId.value as string,
      sessionId: lastItem.sessionId as string,
      questionId: lastItem.questionId as string,
      answerContent: lastItem.message as string,
      replyState
    }
    await apiStopQuestion(queryData)
    MessageList.value[MessageList.value.length - 1].answerState =
      replyState > 2 ? EAnswerState.OVERTIME : EAnswerState.INTERRUPT
    MessageList.value[MessageList.value.length - 1].replyState = replyState
    sentPending.value = false

    sessionIdValue.value = props.sessionId
    console.log('stopQuestion', MessageList.value)
    console.warn('stopQuestion')
    // stopSentPending()
  }
}

function startWaitingAnswer(args: any) {
  console.log('startWaitingAnswer', args)
}

const isDisabledAsk = computed(
  () => currentMessage.value.length === 0 || (props.isDocument && props.processStatus !== 6)
)

function onClickRelatedItem(title: string) {
  if (sentPending.value) return
  sendQuestion({ message: title })
}
// const toggleInputType = console.log
const onConfirm = () => {
  if (isDisabledAsk.value || sentPending.value) return
  sendQuestion()
}
const onInputChange = console.log
// const toggleTextareaFullscreen = console.log
const onClickSendBtn = () => {
  console.log('onClickSendBtn', sentPending.value)
  if (sentPending.value) {
    stopQuestion()
    return
  }
  if (isDisabledAsk.value) return
  sendQuestion()
}

const onkeydown = (e: KeyboardEvent) => {
  if (e.key === 'Enter' && e.shiftKey) {
    const target = e.target as HTMLInputElement
    // 获取光标位置
    const cursorPosition: number = target?.selectionStart || 0
    // 在光标位置插入换行
    currentMessage.value =
      currentMessage.value.substring(0, cursorPosition) +
      '\n' +
      currentMessage.value.substring(cursorPosition)

    nextTick(() => {
      ;(textarea.value as ComponentPublicInstance)?.$el
        .querySelector('textarea')
        ?.setSelectionRange(cursorPosition + 1, cursorPosition + 1)
    })
    // 阻止原生的换行事件
    e.preventDefault()
  } else if (e.key === 'Enter') {
    // 阻止原生的换行事件
    e.preventDefault()
    onConfirm()
  }
}
const closeCurrentPage = () => {
  currentPaper.value = undefined
  console.log('closeCurrentPage', currentPaper.value)
}
onBeforeUnmount(() => {
  console.log('onBeforeUnmount')
  socketClose()
})
const ansyizeing = ref()
const initLottie = () => {
  const container = ansyizeing.value
  console.log('container', container)
  ansyizeing.value = lottie.loadAnimation({
    container: container,
    renderer: 'svg',
    loop: true,
    autoplay: true,
    name: 'demo',
    rendererSettings: {
      imagePreserveAspectRatio: 'meet'
    },
    animationData: {
      nm: 'Main Scene',
      ddd: 0,
      h: 400,
      w: 400,
      meta: { g: '@lottiefiles/creator 1.28.0' },
      layers: [
        {
          ty: 4,
          nm: 'Shape Layer 5',
          sr: 1,
          st: 20,
          op: 620,
          ip: 20,
          hd: false,
          ddd: 0,
          bm: 0,
          hasMask: false,
          ao: 0,
          ks: {
            a: { a: 0, k: [0, 0, 0] },
            s: { a: 0, k: [100, 100, 100] },
            sk: { a: 0, k: 0 },
            p: { a: 0, k: [251, 250, 0] },
            r: {
              a: 1,
              k: [
                { o: { x: 0.333, y: 0 }, i: { x: 0.667, y: 1 }, s: [0], t: 20 },
                { s: [360], t: 110 }
              ]
            },
            sa: { a: 0, k: 0 },
            o: { a: 0, k: 100 }
          },
          shapes: [
            {
              ty: 'gr',
              bm: 0,
              hd: false,
              mn: 'ADBE Vector Group',
              nm: 'Ellipse 1',
              ix: 1,
              cix: 2,
              np: 3,
              it: [
                {
                  ty: 'el',
                  bm: 0,
                  hd: false,
                  mn: 'ADBE Vector Shape - Ellipse',
                  nm: 'Ellipse Path 1',
                  d: 1,
                  p: { a: 0, k: [0, -100] },
                  s: { a: 0, k: [10, 10] }
                },
                {
                  ty: 'st',
                  bm: 0,
                  hd: false,
                  mn: 'ADBE Vector Graphic - Stroke',
                  nm: 'Stroke 1',
                  lc: 1,
                  lj: 1,
                  ml: 4,
                  o: { a: 0, k: 100 },
                  w: { a: 0, k: 0 },
                  c: { a: 0, k: [0, 0, 0] }
                },
                {
                  ty: 'fl',
                  bm: 0,
                  hd: false,
                  mn: 'ADBE Vector Graphic - Fill',
                  nm: 'Fill 1',
                  c: { a: 0, k: [0.3569, 0.6549, 0.9686] },
                  r: 1,
                  o: { a: 0, k: 100 }
                },
                {
                  ty: 'tr',
                  a: { a: 0, k: [0, 0] },
                  s: { a: 0, k: [100, 100] },
                  sk: { a: 0, k: 0 },
                  p: { a: 0, k: [0, 0] },
                  r: { a: 0, k: 0 },
                  sa: { a: 0, k: 0 },
                  o: { a: 0, k: 100 }
                }
              ]
            }
          ],
          ind: 1
        },
        {
          ty: 4,
          nm: 'Shape Layer 4',
          sr: 1,
          st: 15,
          op: 615,
          ip: 15,
          hd: false,
          ddd: 0,
          bm: 0,
          hasMask: false,
          ao: 0,
          ks: {
            a: { a: 0, k: [0, 0, 0] },
            s: { a: 0, k: [100, 100, 100] },
            sk: { a: 0, k: 0 },
            p: { a: 0, k: [251, 250, 0] },
            r: {
              a: 1,
              k: [
                { o: { x: 0.333, y: 0 }, i: { x: 0.667, y: 1 }, s: [0], t: 15 },
                { s: [360], t: 105 }
              ]
            },
            sa: { a: 0, k: 0 },
            o: { a: 0, k: 100 }
          },
          shapes: [
            {
              ty: 'gr',
              bm: 0,
              hd: false,
              mn: 'ADBE Vector Group',
              nm: 'Ellipse 1',
              ix: 1,
              cix: 2,
              np: 3,
              it: [
                {
                  ty: 'el',
                  bm: 0,
                  hd: false,
                  mn: 'ADBE Vector Shape - Ellipse',
                  nm: 'Ellipse Path 1',
                  d: 1,
                  p: { a: 0, k: [0, -100] },
                  s: { a: 0, k: [20, 20] }
                },
                {
                  ty: 'st',
                  bm: 0,
                  hd: false,
                  mn: 'ADBE Vector Graphic - Stroke',
                  nm: 'Stroke 1',
                  lc: 1,
                  lj: 1,
                  ml: 4,
                  o: { a: 0, k: 100 },
                  w: { a: 0, k: 0 },
                  c: { a: 0, k: [0, 0, 0] }
                },
                {
                  ty: 'fl',
                  bm: 0,
                  hd: false,
                  mn: 'ADBE Vector Graphic - Fill',
                  nm: 'Fill 1',
                  c: { a: 0, k: [0.3569, 0.6549, 0.9686] },
                  r: 1,
                  o: { a: 0, k: 100 }
                },
                {
                  ty: 'tr',
                  a: { a: 0, k: [0, 0] },
                  s: { a: 0, k: [100, 100] },
                  sk: { a: 0, k: 0 },
                  p: { a: 0, k: [0, 0] },
                  r: { a: 0, k: 0 },
                  sa: { a: 0, k: 0 },
                  o: { a: 0, k: 100 }
                }
              ]
            }
          ],
          ind: 2
        },
        {
          ty: 4,
          nm: 'Shape Layer 3',
          sr: 1,
          st: 10,
          op: 610,
          ip: 10,
          hd: false,
          ddd: 0,
          bm: 0,
          hasMask: false,
          ao: 0,
          ks: {
            a: { a: 0, k: [0, 0, 0] },
            s: { a: 0, k: [100, 100, 100] },
            sk: { a: 0, k: 0 },
            p: { a: 0, k: [251, 250, 0] },
            r: {
              a: 1,
              k: [
                { o: { x: 0.333, y: 0 }, i: { x: 0.667, y: 1 }, s: [0], t: 10 },
                { s: [360], t: 100 }
              ]
            },
            sa: { a: 0, k: 0 },
            o: { a: 0, k: 100 }
          },
          shapes: [
            {
              ty: 'gr',
              bm: 0,
              hd: false,
              mn: 'ADBE Vector Group',
              nm: 'Ellipse 1',
              ix: 1,
              cix: 2,
              np: 3,
              it: [
                {
                  ty: 'el',
                  bm: 0,
                  hd: false,
                  mn: 'ADBE Vector Shape - Ellipse',
                  nm: 'Ellipse Path 1',
                  d: 1,
                  p: { a: 0, k: [0, -100] },
                  s: { a: 0, k: [30, 30] }
                },
                {
                  ty: 'st',
                  bm: 0,
                  hd: false,
                  mn: 'ADBE Vector Graphic - Stroke',
                  nm: 'Stroke 1',
                  lc: 1,
                  lj: 1,
                  ml: 4,
                  o: { a: 0, k: 100 },
                  w: { a: 0, k: 0 },
                  c: { a: 0, k: [0, 0, 0] }
                },
                {
                  ty: 'fl',
                  bm: 0,
                  hd: false,
                  mn: 'ADBE Vector Graphic - Fill',
                  nm: 'Fill 1',
                  c: { a: 0, k: [0.3569, 0.6549, 0.9686] },
                  r: 1,
                  o: { a: 0, k: 100 }
                },
                {
                  ty: 'tr',
                  a: { a: 0, k: [0, 0] },
                  s: { a: 0, k: [100, 100] },
                  sk: { a: 0, k: 0 },
                  p: { a: 0, k: [0, 0] },
                  r: { a: 0, k: 0 },
                  sa: { a: 0, k: 0 },
                  o: { a: 0, k: 100 }
                }
              ]
            }
          ],
          ind: 3
        },
        {
          ty: 4,
          nm: 'Shape Layer 2',
          sr: 1,
          st: 5,
          op: 605,
          ip: 5,
          hd: false,
          ddd: 0,
          bm: 0,
          hasMask: false,
          ao: 0,
          ks: {
            a: { a: 0, k: [0, 0, 0] },
            s: { a: 0, k: [100, 100, 100] },
            sk: { a: 0, k: 0 },
            p: { a: 0, k: [251, 250, 0] },
            r: {
              a: 1,
              k: [
                { o: { x: 0.333, y: 0 }, i: { x: 0.667, y: 1 }, s: [0], t: 5 },
                { s: [360], t: 95 }
              ]
            },
            sa: { a: 0, k: 0 },
            o: { a: 0, k: 100 }
          },
          shapes: [
            {
              ty: 'gr',
              bm: 0,
              hd: false,
              mn: 'ADBE Vector Group',
              nm: 'Ellipse 1',
              ix: 1,
              cix: 2,
              np: 3,
              it: [
                {
                  ty: 'el',
                  bm: 0,
                  hd: false,
                  mn: 'ADBE Vector Shape - Ellipse',
                  nm: 'Ellipse Path 1',
                  d: 1,
                  p: { a: 0, k: [0, -100] },
                  s: { a: 0, k: [40, 40] }
                },
                {
                  ty: 'st',
                  bm: 0,
                  hd: false,
                  mn: 'ADBE Vector Graphic - Stroke',
                  nm: 'Stroke 1',
                  lc: 1,
                  lj: 1,
                  ml: 4,
                  o: { a: 0, k: 100 },
                  w: { a: 0, k: 0 },
                  c: { a: 0, k: [0, 0, 0] }
                },
                {
                  ty: 'fl',
                  bm: 0,
                  hd: false,
                  mn: 'ADBE Vector Graphic - Fill',
                  nm: 'Fill 1',
                  c: { a: 0, k: [0.3569, 0.6549, 0.9686] },
                  r: 1,
                  o: { a: 0, k: 100 }
                },
                {
                  ty: 'tr',
                  a: { a: 0, k: [0, 0] },
                  s: { a: 0, k: [100, 100] },
                  sk: { a: 0, k: 0 },
                  p: { a: 0, k: [0, 0] },
                  r: { a: 0, k: 0 },
                  sa: { a: 0, k: 0 },
                  o: { a: 0, k: 100 }
                }
              ]
            }
          ],
          ind: 4
        },
        {
          ty: 4,
          nm: 'Shape Layer 1',
          sr: 1,
          st: 0,
          op: 600,
          ip: 0,
          hd: false,
          ddd: 0,
          bm: 0,
          hasMask: false,
          ao: 0,
          ks: {
            a: { a: 0, k: [0, 0, 0] },
            s: { a: 0, k: [100, 100, 100] },
            sk: { a: 0, k: 0 },
            p: { a: 0, k: [250, 250, 0] },
            r: {
              a: 1,
              k: [
                { o: { x: 0.333, y: 0 }, i: { x: 0.667, y: 1 }, s: [0], t: 0 },
                { s: [360], t: 90 }
              ]
            },
            sa: { a: 0, k: 0 },
            o: { a: 0, k: 100 }
          },
          shapes: [
            {
              ty: 'gr',
              bm: 0,
              hd: false,
              mn: 'ADBE Vector Group',
              nm: 'Ellipse 1',
              ix: 1,
              cix: 2,
              np: 3,
              it: [
                {
                  ty: 'el',
                  bm: 0,
                  hd: false,
                  mn: 'ADBE Vector Shape - Ellipse',
                  nm: 'Ellipse Path 1',
                  d: 1,
                  p: { a: 0, k: [0, -100] },
                  s: {
                    a: 1,
                    k: [
                      { o: { x: 0.333, y: 0 }, i: { x: 0.667, y: 1 }, s: [50, 50], t: 0 },
                      { o: { x: 0.333, y: 0 }, i: { x: 0.667, y: 1 }, s: [40, 40], t: 84 },
                      { s: [50, 50], t: 100 }
                    ]
                  }
                },
                {
                  ty: 'st',
                  bm: 0,
                  hd: false,
                  mn: 'ADBE Vector Graphic - Stroke',
                  nm: 'Stroke 1',
                  lc: 1,
                  lj: 1,
                  ml: 4,
                  o: { a: 0, k: 100 },
                  w: { a: 0, k: 0 },
                  c: { a: 0, k: [0, 0, 0] }
                },
                {
                  ty: 'fl',
                  bm: 0,
                  hd: false,
                  mn: 'ADBE Vector Graphic - Fill',
                  nm: 'Fill 1',
                  c: { a: 0, k: [0.3569, 0.6549, 0.9686] },
                  r: 1,
                  o: { a: 0, k: 100 }
                },
                {
                  ty: 'tr',
                  a: { a: 0, k: [0, 0] },
                  s: { a: 0, k: [100, 100] },
                  sk: { a: 0, k: 0 },
                  p: { a: 0, k: [0, 0] },
                  r: { a: 0, k: 0 },
                  sa: { a: 0, k: 0 },
                  o: { a: 0, k: 100 }
                }
              ]
            }
          ],
          ind: 5
        }
      ],
      v: '5.7.0',
      fr: 60,
      op: 106,
      ip: 0,
      assets: []
    }
  })
}

const referenceContent = ref()
const handlePageChange = (paperId: string | number, id: string) => {
  console.log(paperId, id, '213')
  referenceContent.value?.resetFilter?.()
  const item: MainItemVo =
    MessageList.value.filter((item) => item.id === id).length > 0
      ? MessageList.value.filter((item) => item.id === id)[0]
      : {}
  referenceIndex.value = ''
  let index
  if (!Number.isInteger(Number(paperId))) {
    index = item?.resourceIds?.findIndex((c) => c === paperId)
  } else {
    index = paperId as number
  }

  showDetail(item, index + 1)
}
provide(scroll, debounceToBottom)

const updateFlowing = (answerId: string, isFlowing: boolean, subIndex: number) => {
  const index = MessageList.value.findIndex(
    (item) => item.answerId === answerId && item.type === 'received'
  )
  MessageList.value[index].isFlowing = isFlowing
  if (MessageList.value[index]?.answerContentList) {
    MessageList.value[index].answerContentList[subIndex].isFlowing = isFlowing
  }
}
provide('updateFlowing', updateFlowing)

const goLogin = () => {
  router.replace({
    path: '/',
    query: {
      // 这里加一个参数，对话 id ，到时候登录成功之后跳转到这个对话
      redirect: `/chat/loginShareMessage/${route.params.id}`
    }
  })
}

type ShareSelectState = {
  indeterminate: boolean
  checkAll: boolean
  checkedList: string[]
}
const shareSelectState = reactive<ShareSelectState>({
  indeterminate: true,
  checkAll: false,
  checkedList: []
})
const onCheckAllChange = (e: any) => {
  Object.assign(shareSelectState, {
    checkedList: e.target.checked ? MessageList.value?.map((c) => c.id) : [],
    indeterminate: false
  })
}

watch(
  () => shareSelectState.checkedList,
  (val) => {
    shareSelectState.indeterminate = !!val.length && val.length < MessageList.value.length
    shareSelectState.checkAll = val.length === MessageList.value.length
  }
)

const cancelSelect = () => {
  isSelecting.value = false
  shareSelectState.checkedList = []
  shareSelectState.indeterminate = false
  shareSelectState.checkAll = false
}

const { copy } = useClipboard()
function removeItemFromArray(array: string[], itemToRemove: string) {
  return array.filter((item) => item !== itemToRemove)
}
const copyLink = async () => {
  if (!shareSelectState.checkedList.length) return msgHelper.error('请选择要复制的内容')
  // console.warn(location.origin,'location.origin',shareSelectState.checkedList,MessageList.value);
  const selectMessageList: Array<MainItemVo> = MessageList.value.filter((item) =>
    shareSelectState.checkedList.includes(item.id as string)
  )
  let ids = [...shareSelectState.checkedList]
  const copilotConversationShareReqs = selectMessageList.reduce(
    (acc: any[], cur: MainItemVo): any[] => {
      // console.warn(ids,'ids1',JSON.parse(JSON.stringify(acc)),selectMessageList);

      if (!ids.length || !ids.includes(cur.id as string)) return acc
      if (cur.type === 'sent') {
        ids = removeItemFromArray(ids, cur.id as string)
        if (ids.includes(cur.answerId as string)) {
          ids = removeItemFromArray(ids, cur.answerId as string)
          acc.push({ id: cur.groupId, shareType: 0 })
          return acc
        }
        acc.push({ id: cur.groupId, shareType: 1 })
        return acc
      } else {
        ids = removeItemFromArray(ids, cur.id as string)
        if (ids.includes(cur.questionId as string)) {
          ids = removeItemFromArray(ids, cur.questionId as string)
          acc.push({ id: cur.groupId, shareType: 0 })
          return acc
        }
        acc.push({ id: cur.groupId, shareType: 2 })
        return acc
      }
    },
    []
  )

  // console.warn(copilotConversationShareReqs, 'copilotConversationShareReqs')
  const {
    data: { entity = '' }
  } = await apiShareRecorder({ copilotConversationShareReqs })
  // console.warn(entity, 'res123123')

  copy(`${location.origin}/shareMessage/${entity}`)
  msgHelper.success('分享链接复制成功！')
}
</script>

<style lang="scss" scoped>
.chat-room-container {
  padding: 0;
  height: 100%;
}

@keyframes twinkle {
  0% {
    transform: scale(1);
  }

  100% {
    transform: scale(1.08);
  }
}

.chat-room {
  width: 100%;

  display: flex;
  justify-content: center;

  background: #f5f6f8;
  padding: 0 0;

  .chat-room-inside {
    height: 100%;
    overflow-x: hidden;
    position: relative;
    padding: 0 0;
    display: flex;
    flex-flow: column nowrap;
    margin: 0 auto;
    flex-basis: 800px;
    .to-bottom-btn {
      position: absolute;
      z-index: 10;
      bottom: 108px;
      left: 50%;
      transform: translateX(-50%);
      cursor: pointer;
      background-color: pink;
      width: 60px;
      height: 60px;
      background: url('@/static/image/to_bottom.png') no-repeat;
      background-size: 100% 100%;
    }

    .from-share-btns {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-right: unset;
      span,
      .btn-normal {
        cursor: pointer;
        flex: 1;
        max-width: 48%;
        text-align: center;
        padding: 8px 0;
        border: 1px solid #3c7bff;
        border-radius: 4px;
        background-color: #fff;
        color: #3c7bff;
      }
      .btn-primary {
        background-color: #3c7bff;
        color: #fff;
      }
      .copy-area {
        width: 400px;
        .btn-primary {
          flex: 3;
          max-width: unset;
        }
      }
    }
  }
}

.doc-background {
  background-color: #fff;
}

.chat-history {
  flex: auto;
  display: flex;
  flex-flow: column nowrap;
  justify-content: flex-start;
  align-items: center;
  padding: 20px 36px 0;
  box-sizing: border-box;
  overflow-y: auto;
  .message-list {
    width: 100%;
    box-sizing: border-box;

    // overflow-y: scroll;
    .welcome-msg {
      margin-bottom: 50px;
      justify-content: flex-start;
      background: #fff;
      display: flex;
      flex-flow: row nowrap;
      align-items: flex-start;
      font-size: 14px;
      border-radius: 8px;
      border-top-left-radius: 0;
      padding: 16px 20px;
      background-color: #f8fafc;
    }
    .message-item {
      &.answer.doc-background {
        background-color: #f8fafc;
      }
    }
  }

  .mock-checkbox {
    margin-top: 17px;
    width: 42px;
    height: 42px;
    border-radius: 42px;
    margin-right: 25px;
    background-image: url('@/static/image/ic_circle_uncheck.png');
    background-size: 42px 42px;
    background-repeat: no-repeat;
    background-position: center center;

    &.checked {
      background-image: url('@/static/image/ic_circle_check.png');
    }
  }
}

.recommend-wrap {
  width: 100%;

  .recommend-banner {
    width: 100%;
    height: 220px;
    border-radius: 16px;
    margin: 24px 0 20px 0;
  }

  .recommend-title {
    text-align: left;
    padding-left: 10px;
    color: #10121a;
    font-weight: bold;
    font-size: 28px;
    margin: 20px 0;
  }

  .recommend-list {
    border-radius: 16px;
    font-size: 26px;
    background-color: #fff;

    .recommend-item {
      display: flex;
      flex-flow: row nowrap;
      align-items: center;
      justify-content: space-between;
      min-height: 70px;
      padding: 10px 25px;
      border-bottom: 0.5px solid #f0f0f0ff;
      font-size: 14px;
      color: #10121a;

      .text {
        max-width: 95%;
      }

      .icon-arrow {
        width: 24px;
        height: 24px;
      }
    }
  }
}

.chat-input {
  // flex: 0;
  // display: flex;
  // flex-flow: row nowrap;
  // justify-content: space-between;
  // align-items: stretch;
  position: relative;
  font-size: 16px;
  // background-color: #fff;
  padding: 16px 36px 30px;
  z-index: 1;

  &::after {
    content: '以上内容均由AI生成，仅供参考和借鉴';
    position: absolute;
    bottom: 8px;
    left: 50%;
    transform: translate(-50%, 0);
    font-size: 14px;
    color: #9a9eab;
    white-space: nowrap;
  }

  div {
    margin-right: 8px;
  }

  .text-tools-wrap {
    // overflow: hidden;
    flex: auto;
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    align-items: end;
    box-sizing: border-box;
    border: 1px solid rgba(112, 124, 151, 0.25);
    border-radius: 8px;
    padding: 7px 0;
    margin-bottom: 6px;
    margin-right: unset;
    position: relative;
    background: #fff;

    .flex-center {
      display: flex;
      align-items: center;
    }

    .flex-none {
      flex: none;
    }

    .button-list {
      position: absolute;
      border: 1px solid #dbdee2;
      border-radius: 8px;
      z-index: 100;
      bottom: 0;
      background: #fff;
      bottom: 10px;
      left: 10px;

      .answerTypeItem {
        padding: 0px 12px;
        cursor: pointer;
        height: 36px;
        display: flex;
        align-items: center;
        margin-right: 0px;
      }

      .answerTypeIcon {
        width: 20px;
        height: 20px;
        margin-right: 6px;
      }
    }

    .singleTypeItem {
      height: 36px;
      display: flex;
      align-items: center;

      .answerTypeItem {
        margin-bottom: 0px;
        margin-right: 0;
      }
    }

    .textarea-wrap {
      position: relative;
      flex: auto;
      align-self: stretch;

      ::v-deep textarea {
        border: none;
        box-shadow: none;
        line-height: 30px;
      }
      :deep() .ant-input::placeholder {
        color: #a3a4a5;
      }
    }
  }

  .btn-send {
    background-image: url('@/static/image/send-active.png');
    background-repeat: no-repeat;
    background-position: center center;
    background-size: 100% 100%;
    width: 40px;
    height: 40px;
    cursor: pointer;

    &.disabled {
      background-image: url('@/static/image/send.png');
      box-shadow: none;
      cursor: no-drop;
    }
  }
  .btn-stop-send {
    background-image: url('@/static/image/stop_send.png');
    background-repeat: no-repeat;
    background-position: center center;
    background-size: 100% 100%;
    width: 40px;
    height: 40px;
    cursor: pointer;
  }

  .space-between {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.flex {
  display: flex;
  align-items: center;
}

.action-area.action-area {
  color: #3d3d3d;
  font-size: 14px;
  margin-right: unset;

  .clear-records {
    cursor: pointer;

    &:hover {
      .icon-brush-wrap {
        background: #f3f5f8;
      }
    }
  }

  .enhance-btn {
    cursor: pointer;
    margin-right: unset;

    span {
      margin-left: 6px;
    }
  }
}

.icon-brush-wrap {
  border: 1px solid #dbdee2;
  background-color: #fff;
  justify-content: center;
  flex-flow: row nowrap;
  border-radius: 100px;
  align-items: center;
  cursor: pointer;
  display: flex;
  z-index: 200;
  height: 24px;
  width: 24px;
  margin-right: 10px;

  .icon-brush {
    width: 14px;
    height: 14px;
  }

  &:hover {
    background: #f3f5f8;
  }
}
.ansyizeing {
  width: 40px;
  height: 40px;
}
.divider {
  flex: 0 0 4px;
  height: 100%;
  background-color: #f0f0f0;
  cursor: col-resize;

  &:active {
    cursor: default;
  }
}
.reference-content {
  max-width: 30%;
}
.chatCreatedTime {
  position: absolute;
  right: 24px;
  bottom: -16px;
  color: #5c5e61;
  font-size: 14px;
}
::v-deep .ant-input-clear-icon {
  top: 13px;
}
.no-data {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
